package controller;

import entity.*;
import http_post.src.Sendsms;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

import relationEntity.OrderTheme;
import relationEntity.OrderUser;
import relationEntity.PhotoTheme;
import service.PhotographerService;
import service.UserService;
import util.CreateOrder;
import util.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by jifeng on 2017/2/9 0009.高校摄影
 */
@Controller
public class PhotographerController {
	@Resource(name = "photographerService")
	private PhotographerService photographerService;
	@Resource(name = "userService")
	private UserService service;

	/**
	 * 摄影商品列表
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/themeList")
	public Model themeList(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		List<PhotoTheme> photoThemeList = photographerService.findPhotoTheme();
		mv.addAttribute("photoThemeList", photoThemeList);
		return mv;
	}

	/**
	 * 主题商品的明细
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/themeDetail")
	public Model themeDetail(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeIdStr = request.getParameter("themeId");
		if (!StringUtils.isEmpty(themeIdStr)) {
			int themeIdInt = Integer.parseInt(themeIdStr);
			Theme themeIns = photographerService.findThemeById(themeIdInt);
			mv.addAttribute("themeIns", themeIns);
		}

		return mv;
	}

	/**
	 * 主题商品的明细
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/editTheme")
	public Model themeEdit(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeIdStr = request.getParameter("themeId");
		if (!StringUtils.isEmpty(themeIdStr)) {
			int themeIdInt = Integer.parseInt(themeIdStr);
			Theme themeIns = photographerService.findThemeById(themeIdInt);
			mv.addAttribute("themeIns", themeIns);
			mv.addAttribute("content1", themeIns.getDetails());
		}

		List<Photographer> photographerList = photographerService
				.findPhotographerList();
		mv.addAttribute("photographerList", photographerList);

		return mv;
	}

	/**
	 * 主题商品的明细
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/delTheme")
	public String themeDel(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeIdStr = request.getParameter("themeId");
		if (!StringUtils.isEmpty(themeIdStr)) {
			int themeIdInt = Integer.parseInt(themeIdStr);
			photographerService.deleteThemeById(themeIdInt);
		}
		return "redirect:/themeList";
	}

	/**
	 * 更改订单
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/editThemeOrder")
	public Model editThemeOrder(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String photoOrderIdStr = request.getParameter("orderId");
		if (!StringUtils.isEmpty(photoOrderIdStr)) {
			int photoOrderIdInt = Integer.parseInt(photoOrderIdStr);
			OrderTheme orderThemeIns = photographerService
					.findOrderThemeById(photoOrderIdInt);
			mv.addAttribute("orderThemeIns", orderThemeIns);
		}

		return mv;
	}

	/**
	 * 更改订单
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/updateThemeOrder")
	public String updateThemeOrder(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeOrderIdStr = request.getParameter("themeOrderId");
		String themeStatus = request.getParameter("themeOrderStatus");
		String cloudAddress = request.getParameter("cloudAddress");
		String extractedCode = request.getParameter("extractedCode");
		if (!StringUtils.isEmpty(themeOrderIdStr)) {
			int themeOrderId = Integer.parseInt(themeOrderIdStr);
			photographerService.updatePHOrderStatus(themeOrderId, themeStatus,
					cloudAddress, extractedCode);
		}

		return "redirect:/photoorderList";
	}

	/**
	 * Created by jifeng 增加主题商品
	 */
	@RequestMapping(value = "/demo")
	public Model demo(HttpServletRequest request, HttpServletResponse response,
			Model mv) {
		String photographerId = request.getParameter("photographerId");
		List<Photographer> photographerList = photographerService
				.findPhotographerList();
		mv.addAttribute("photographerList", photographerList);
		mv.addAttribute("photographerId", photographerId);
		return mv;
	}

	/**
	 * 主题商品的明细
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/updateTheme")
	public String updateTheme(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		String content1 = request.getParameter("content1");
		String photographerId = request.getParameter("photographerId");
		String themeId = request.getParameter("themeId");

		String themeTitle = request.getParameter("themeTitle");
		String themePrice = request.getParameter("themePrice");
		String themeDuration = request.getParameter("themeDuration");
		String themeNegative = request.getParameter("themeNegative");
		String themeDecoration = request.getParameter("themeDecoration");
		String themeSeries = request.getParameter("themeSeries");
		String themeRankValue = request.getParameter("themeRankValue");

		if (!StringUtils.isEmpty(themeId)) {
			Theme theme = photographerService.findThemeById(Integer
					.parseInt(themeId));
			if (theme != null) {
				theme.setDetails(content1);
				theme.setPhotographerId(Integer.valueOf(photographerId));
				theme.setThemeName(themeTitle);
				theme.setPrice(Long.parseLong(themePrice));
				theme.setDuration(Integer.parseInt(themeDuration));
				theme.setNegative(Integer.parseInt(themeNegative));
				theme.setDecoration(Integer.parseInt(themeDecoration));
				theme.setSeries(Integer.parseInt(themeSeries));
				theme.setRankValue(Integer.parseInt(themeRankValue));

				// 获得物理路径webapp所在路径
				String pathRoot = request.getSession().getServletContext()
						.getRealPath("");
				String path = "";
				if (!file.isEmpty()) {
					// 生成uuid作为文件名称
					String uuid = (int) (Math.random() * 1000000) + "";
					// 获得文件类型（可以判断如果不是图片，禁止上传）
					String contentType = file.getContentType();
					// 获得文件后缀名称
					String imageName = contentType.substring(contentType
							.indexOf("/") + 1);
					path = "/image/image/" + uuid + "." + imageName;
					file.transferTo(new File(pathRoot + path));
					theme.setAdvertisingMap(path);
					theme.setPhoto(path);
				}

				photographerService.updateTheme(theme);
				System.out.print(content1);
			}
		}

		return "redirect:/themeList";
	}

	/**
	 * Created by jifeng 测试富文编辑器显示页面
	 * 
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "/demos")
	public String demos(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		String content1 = request.getParameter("content1");
		String photographerId = request.getParameter("photographerId");

		String themeTitle = request.getParameter("themeTitle");
		String themePrice = request.getParameter("themePrice");
		String themeDuration = request.getParameter("themeDuration");
		String themeNegative = request.getParameter("themeNegative");
		String themeDecoration = request.getParameter("themeDecoration");
		String themeSeries = request.getParameter("themeSeries");
		String themeRankValue = request.getParameter("themeRankValue");

		// 获得物理路径webapp所在路径
		String pathRoot = request.getSession().getServletContext()
				.getRealPath("");
		String path = "";
		if (!file.isEmpty()) {
			// 生成uuid作为文件名称
			String uuid = (int) (Math.random() * 1000000) + "";
			// 获得文件类型（可以判断如果不是图片，禁止上传）
			String contentType = file.getContentType();
			// 获得文件后缀名称
			String imageName = contentType
					.substring(contentType.indexOf("/") + 1);
			path = "/image/image/" + uuid + "." + imageName;
			file.transferTo(new File(pathRoot + path));
		}
		System.out.println(path);
		request.setAttribute("imagesPath", path);

		Theme theme = new Theme();
		theme.setDetails(content1);
		theme.setPhotographerId(Integer.valueOf(photographerId));
		theme.setThemeName(themeTitle);
		theme.setPrice(Long.parseLong(themePrice));
		theme.setDuration(Integer.parseInt(themeDuration));
		theme.setNegative(Integer.parseInt(themeNegative));
		theme.setDecoration(Integer.parseInt(themeDecoration));
		theme.setSeries(Integer.parseInt(themeSeries));
		theme.setAdvertisingMap(path);
		theme.setPhoto(path);
		theme.setRankValue(Integer.parseInt(themeRankValue));
		photographerService.saveTheme(theme);
		System.out.print(content1);
		/*
		 * mv.addAttribute("photographerId",photographerId);
		 * mv.addAttribute("content",content1);
		 */
		return "redirect:/themeList";
	}

	@RequestMapping(value = "/addPhotographer")
	public Model addPhotographer(HttpServletRequest request,
			HttpServletResponse response, Model mv)
			throws IllegalStateException, IOException {

		return mv;
	}

	@RequestMapping(value = "/prepareEditPhotographer")
	public Model prepareEditPhotographer(HttpServletRequest request,
			HttpServletResponse response, Model mv)
			throws IllegalStateException, IOException {
		String photographerId = request.getParameter("photographerId");
		if (!StringUtils.isEmpty(photographerId)) {
			Photographer photographer = photographerService
					.findPhotographerById(Integer.parseInt(photographerId));
			mv.addAttribute("photographer", photographer);
		}

		return mv;
	}

	// updatePhotographer

	@RequestMapping(value = "/updatePhotographer")
	public String updatePhotographer(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		String photographerId = request.getParameter("photographerId");
		String name = request.getParameter("name");
		String briefintro = request.getParameter("briefintro");
		String appointment = request.getParameter("appointment");
		String experience = request.getParameter("experience");

		if (!StringUtils.isEmpty(photographerId)) {
			Photographer photographer = photographerService
					.findPhotographerById(Integer.parseInt(photographerId));
			if (photographer != null) {

				if (!StringUtils.isEmpty(name))
					photographer.setName(name);
				if (!StringUtils.isEmpty(experience))
					photographer.setExperience(Integer.parseInt(experience));
				if (!StringUtils.isEmpty(appointment))
					photographer.setAppointment(Integer.parseInt(appointment));
				if (!StringUtils.isEmpty(briefintro))
					photographer.setBriefintro(briefintro);

				// 获得物理路径webapp所在路径
				String pathRoot = request.getSession().getServletContext()
						.getRealPath("");
				String path = "";
				if (!file.isEmpty()) {
					// 生成uuid作为文件名称
					String uuid = (int) (Math.random() * 1000000) + "";
					// 获得文件类型（可以判断如果不是图片，禁止上传）
					String contentType = file.getContentType();
					// 获得文件后缀名称
					String imageName = contentType.substring(contentType
							.indexOf("/") + 1);
					path = "/image/image/" + uuid + "." + imageName;
					file.transferTo(new File(pathRoot + path));
					photographer.setHeadPortrait(path);
				}

				photographerService.updatePhotographer(photographer);
			}
		}

		return "redirect:/photographerList";
	}

	@RequestMapping(value = "/savePhotographer")
	public String savePhotographer(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {

		Photographer photographer = new Photographer();
		// photographer.setStartDate(new Date());

		String name = request.getParameter("name");
		photographer.setName(name);

		String describe = request.getParameter("describe");
		photographer.setBriefintro(describe);
		String appointment = request.getParameter("appointment");
		if (!StringUtils.isEmpty(appointment))
			photographer.setAppointment(Integer.parseInt(appointment));

		String experience = request.getParameter("experience");
		if (!StringUtils.isEmpty(experience))
			photographer.setExperience(Integer.parseInt(experience));

		// 获得物理路径webapp所在路径
		String pathRoot = request.getSession().getServletContext()
				.getRealPath("");
		String path = "";
		if (!file.isEmpty()) {
			// 生成uuid作为文件名称
			String uuid = (int) (Math.random() * 1000000) + "";
			// 获得文件类型（可以判断如果不是图片，禁止上传）
			String contentType = file.getContentType();
			// 获得文件后缀名称
			String imageName = contentType
					.substring(contentType.indexOf("/") + 1);
			path = "/image/image/" + uuid + "." + imageName;
			file.transferTo(new File(pathRoot + path));
		}
		System.out.println(path);
		photographer.setHeadPortrait(path);
		photographer.setAddress("");
		photographer.setOtherName("");
		photographer.setSex("");
		photographer.setAddress("");
		photographerService.savePhotographer(photographer);
		/*
		 * mv.addAttribute("photographerId",photographerId);
		 * mv.addAttribute("content",content1);
		 */
		return "redirect:/photographerList";
	}

	/**
	 * Created by jifeng 咔嗒跳转登录面
	 */
	@RequestMapping(value = "/photographerList")
	public Model photographerList(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		List<Photographer> photographerList = photographerService
				.findPhotographerList();
		mv.addAttribute("photographerList", photographerList);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒跳转登录面
	 */
	@RequestMapping(value = "/kaLogin")
	public Model kaLogin(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String resp = String.valueOf(request.getSession().getAttribute("resp"));
		mv.addAttribute("resp", resp);
		request.getSession().removeAttribute("resp");
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒登录
	 */
	@RequestMapping(value = "/toKaLogin")
	public String toKaLogin(HttpServletRequest request,
			HttpServletResponse response) {
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		List<User> userList = service.findUserByPhonePd(phone, password);
		if (userList.size() == 0) {
			int resp = 10;
			request.getSession().setAttribute("resp", resp);
			return "redirect:/kaLogin";
		} else {
			User user = service.findUserByPhone(phone).get(0);
			request.getSession().setAttribute("userId", user.getId());
			Object themeIdObj = request.getSession().getAttribute(
					"THEMEID_BEFORE_LOGIN");
			if (themeIdObj != null) {
				String themeId = String.valueOf(themeIdObj);
				if (!StringUtils.isEmpty(themeId)) {
					return "redirect:/kaSampleDet?themeId=" + themeId;
				}
			}
			return "redirect:/kdIndex";
		}
	}
	
	@RequestMapping(value = "/kaForgetPwd")
	public Model kaForgetpwd(HttpServletRequest request, HttpServletResponse response, Model mv) {
		String errCode = String.valueOf(request.getParameter("errCode"));
		if (errCode != null) {
			if (errCode.equals("1")) {
				String resp = "验证码不匹配!";
				mv.addAttribute("resp", resp);
			}
		} else {
			request.getSession().removeAttribute("resp");
		}
		
		request.getSession().removeAttribute("password");
		return mv;
	}

	/**
	 * Created by jifeng 忘记密码
	 */
	@RequestMapping(value = "/kaUpdatePwd")
	public String kaUpdatePwd(HttpServletRequest request, HttpServletResponse response, Model mv) {
		String phoneNum = String.valueOf(request.getParameter("phone"));
		String newPwd = String.valueOf(request.getParameter("password"));
		String yzm = String.valueOf(request.getParameter("zc"));
		
		String mobile_code = String.valueOf(request.getSession().getAttribute("mobile_code"));

		String resp = null;
		if (mobile_code != null && mobile_code.equals(yzm)) {
			User user = new User();
			user.setPhone(phoneNum);
			user.setPassword(newPwd);
			service.updateUser(user);
			request.getSession().removeAttribute("password");
			request.getSession().removeAttribute("phone");
			request.getSession().setAttribute("resp", 2);
			return "redirect:/kaLogin?resp=2";
		} else {
			resp = "验证码错误!";
			return "redirect:/kaForgetPwd?errCode=1";
		}
		
	}
	
	/**
	 * Created by jifeng 获取验证码
	 */
	@RequestMapping(value = "/captcha_sends_forget_pwd")
	public String captcha_sends_forget_pwd(HttpServletRequest request, HttpServletResponse response) {
		String phone = request.getParameter("phone");
		Sendsms.captcha(phone, request);
		String mobile_code = String.valueOf(request.getSession().getAttribute("mobile_code"));
		System.out.print(mobile_code);
		return "redirect:/kaForgetPwd";
	}
	
	/**
	 * Created by jifeng 咔嗒跳转注册面
	 */
	@RequestMapping(value = "/kaRegister")
	public Model kaRegister(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String phone = String.valueOf(request.getSession()
				.getAttribute("phone"));
		String password = String.valueOf(request.getSession().getAttribute(
				"password"));
		String resps = String
				.valueOf(request.getSession().getAttribute("resp"));
		String resp = null;
		if (resps != null) {
			if (resps.equals("8")) {
				resp = "对不起号码已存在!";
			}
			if (resps.equals("9")) {
				resp = "验证码错误!";
			}
		}
		mv.addAttribute("resp", resp);
		mv.addAttribute("phone", phone);
		mv.addAttribute("password", password);
		request.getSession().removeAttribute("resp");
		return mv;
	}

	/**
	 * Created by jifeng 获取验证码
	 */
	@RequestMapping(value = "/captcha_sends")
	public String captcha_sends(HttpServletRequest request,
			HttpServletResponse response) {
		String phone = request.getParameter("phone");
		Sendsms.captcha(phone, request);
		String mobile_code = String.valueOf(request.getSession().getAttribute(
				"mobile_code"));
		System.out.print(mobile_code);
		return "redirect:/kaRegister";
	}

	/**
	 * Created by jifeng 注册
	 */
	@RequestMapping(value = "/saveRegisters")
	public String saveRegisters(HttpServletRequest request,
			HttpServletResponse response) {
		long time = System.currentTimeMillis();
		String head = "kaa";
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		String yzm = request.getParameter("zc");
		String captcha = String.valueOf(request.getSession().getAttribute(
				"mobile_code"));
		request.getSession().setAttribute("phone", phone);
		request.getSession().setAttribute("password", password);
		List<User> userList = service.findUserByPhone(phone);
		if (yzm.equals(captcha)) {
			if (userList.size() == 0) {
				User user = new User();
				String userName = head + time;
				String token = time + phone;
				user.setPhone(phone);
				user.setUserName(userName);
				user.setToken(token);
				user.setOrderNum(0);
				user.setDeletes(0);
				user.setSource("wap");
				user.setPassword(password);
				service.addUser(user);
				/* request.getSession().removeAttribute("phone"); */
				request.getSession().removeAttribute("password");
				request.getSession().removeAttribute("resp");
				return "redirect:/kdIndex";
			} else {
				int resp = 8;
				request.getSession().setAttribute("resp", resp);
				return "redirect:/kaRegister";
			}
		} else {
			int resp = 9;
			request.getSession().setAttribute("resp", resp);
			return "redirect:/kaRegister";
		}

	}

	/**
	 * Created by jifeng 咔嗒退出登录
	 */
	@RequestMapping(value = "/outToLogin")
	public String outToLogin(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().removeAttribute("userId");
		return "redirect:/kaLogin";
	}

	/**
	 * Created by jifeng 咔嗒协议
	 */
	@RequestMapping(value = "/kaAgreement")
	public Model kaAgreement(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		return mv;
	}

	/**
	 * Created by jifeng 获取验证码
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/getInvalidHourIntervals")
	public void getInvalidHourIntervals(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String scheduleDate = request.getParameter("scheduleDate");
		List<Photoorder> scheduledHourList = null;
		String result = "";
		if (!StringUtils.isEmpty(scheduleDate)) {
			scheduledHourList = photographerService
					.findScheduledHours(scheduleDate);
			if (scheduledHourList != null) {
				for (Photoorder order : scheduledHourList) {
					result += (order.getScheduleHour() + "-");
				}
			}
		}
		response.getWriter().println(result);
	}

	/**
	 * Created by jifeng 咔嗒专题首页
	 */
	@RequestMapping(value = "/kdIndex")
	public Model kdIndex(HttpServletRequest request,
			HttpServletResponse response, Model mv) {

		List<PhotoTheme> photoThemeList = photographerService.findPhotoTheme();
		request.getSession().removeAttribute("orderCode");
		mv.addAttribute("photoThemeList", photoThemeList);
		return mv;
	}

	@RequestMapping(value = "/kdNotify", method = RequestMethod.POST)
	public void kdNotify(HttpServletRequest request,
			HttpServletResponse response) throws IOException, DocumentException {

		BufferedReader reader = request.getReader();
		String line = "";
		StringBuffer inputString = new StringBuffer();

		while ((line = reader.readLine()) != null) {
			inputString.append(line);
		}
		request.getReader().close();
		System.out.println("----接收到的报文---" + inputString.toString());

		Document doc = DocumentHelper.parseText(inputString.toString());
		Element root = doc.getRootElement();
		Map<String, Object> map = (Map<String, Object>) xml2map(root);
		String out_trade_no = String.valueOf(map.get("out_trade_no"));
		String return_code = String.valueOf(map.get("return_code"));
		String result_code = String.valueOf(map.get("result_code"));

		if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
			photographerService.updateOrder(out_trade_no);
		}
		response.getWriter().write("SUCCESS");
		;
	}

	private Map xml2map(Element e) {
		Map map = new LinkedHashMap();
		List list = e.elements();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Element iter = (Element) list.get(i);
				List mapList = new ArrayList();

				if (iter.elements().size() > 0) {
					Map m = xml2map(iter);
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!(obj instanceof List)) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(m);
						}
						if (obj instanceof List) {
							mapList = (List) obj;
							mapList.add(m);
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), m);
				} else {
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!(obj instanceof List)) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(iter.getText());
						}
						if (obj instanceof List) {
							mapList = (List) obj;
							mapList.add(iter.getText());
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), iter.getText());
				}
			}
		} else
			map.put(e.getName(), e.getText());
		return map;
	}

	/**
	 * Created by jifeng 咔嗒专题照片
	 */
	@RequestMapping("/kdOrderList")
	public Model kdOrderList(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		List<PhotoTheme> photoThemeList = photographerService.findPhotoTheme();
		mv.addAttribute("photoThemeList", photoThemeList);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒专题个人
	 */
	@RequestMapping("/kaPersonal")
	public ModelAndView kaPersonal(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		// String userId="5";
		if (userId != null && userId != "null") {
			User user = service.findUserById(Integer.valueOf(userId));
			mv.addObject("user", user);
			return mv;
		} else {
			mv.setViewName("kaLogin");
			return mv;
		}
	}

	/**
	 * Created by jifeng 咔嗒专题主题详情页
	 */
	@RequestMapping(value = "/kaStory")
	public Model kaStory(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String themeId = request.getParameter("themeId");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		List<PhotoTheme> photoThemeList = photographerService
				.findPhotoThemeById(theme.getPhotographerId());
		List<Appreciate> appreciateList = photographerService
				.findAppreciateList(Integer.valueOf(themeId));
		int type = 0;
		int size = 0;
		List<Appreciate> appreciates = photographerService
				.findAppreciate(Integer.valueOf(themeId));
		size = appreciates.size();

		if (appreciates.size() != 0) {
			type = 1;
		}

		mv.addAttribute("theme", theme);
		mv.addAttribute("name", photoThemeList.get(0).getName());
		mv.addAttribute("photoThemeList", photoThemeList);
		mv.addAttribute("themeId", themeId);
		mv.addAttribute("size", size);
		mv.addAttribute("type", type);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒专题主题详情页
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/kaToggelePraise")
	public void kaToggelePraise(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String themeId = request.getParameter("themeId");
		int result = -1;
		int size = 0;
		if (!StringUtils.isEmpty(userId) && !"null".equals(userId)
				&& !StringUtils.isEmpty(themeId)) {
			int userIdInt = Integer.parseInt(userId);
			int themeIdint = Integer.parseInt(themeId);
			List<Appreciate> list = photographerService.findAppreciateList(
					themeIdint, userIdInt);
			List<Appreciate> allList = photographerService
					.findAppreciate(themeIdint);
			if (allList != null)
				size = allList.size();
			if (list.size() > 0) {
				photographerService.deleteAppreciate(themeIdint, userIdInt);
				result = 0;
				size--;
			} else {
				photographerService.addAppreciate(themeIdint, userIdInt);
				result = 1;
				size++;
			}
		}
		response.getWriter().write(
				"{\"mystatus\":\"" + result + "\",\"total\":\"" + size + "\"}");
	}

	/**
	 * Created by jifeng 咔嗒专题摄影师详情页
	 */
	@RequestMapping(value = "/kaSampleDet")
	public Model kaSampleDet(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeId = request.getParameter("themeId");
		/*
		 * Date d = new Date(); SimpleDateFormat sdf = new
		 * SimpleDateFormat("yyyy-MM-dd"); String dateNowStr = sdf.format(d);
		 * String startDate=dateNowStr+"00:00:00"; String
		 * endDate=dateNowStr+"59:59:59";
		 */
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		Photographer photographer = photographerService
				.findPhotographerById(theme.getPhotographerId());
		List<PhotoTheme> photoThemeList = photographerService
				.findPhotoThemeById(theme.getPhotographerId());
		/*
		 * List<Photoorder>
		 * photoorderList=photographerService.findAppointment(startDate,endDate)
		 * ; int type=0; if (photoorderList.size()>=2){ type=1; }
		 */
		mv.addAttribute("theme", theme);
		mv.addAttribute("photographer", photographer);
		mv.addAttribute("photoThemeList", photoThemeList);
		// mv.addAttribute("type",type);
		mv.addAttribute("themeId", themeId);
		return mv;
	}

	/**
	 * 某个场景的详情图片
	 * 
	 * @param request
	 * @param response
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/kaThemePhotoList")
	public Model kaThemePhotoList(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeId = request.getParameter("themeId");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		Photographer photographer = photographerService
				.findPhotographerById(theme.getPhotographerId());
		// Theme theme = photographerService.findThemeById(1);
		String content = theme.getDetails();
		mv.addAttribute("photoList", this.getImgStr(content));
		mv.addAttribute("photographer", photographer);
		mv.addAttribute("theme", theme);
		return mv;
	}

	private static List<String> getImgStr(String htmlStr) {
		List<String> pics = new ArrayList<String>();
		String img = "";
		Pattern p_image;
		Matcher m_image;
		// String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
		String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			// 得到<img />数据
			img = m_image.group();
			// 匹配<img>中的src数据
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)")
					.matcher(img);
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

	/**
	 * Created by jifeng 咔嗒专题摄影师资料
	 */
	@RequestMapping(value = "/kaPhotographer")
	public Model kaPhotographer(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeId = request.getParameter("themeId");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		Photographer photographer = photographerService
				.findPhotographerById(theme.getPhotographerId());
		List<PhotoTheme> photoThemeList = photographerService
				.findPhotoThemeById(photographer.getId());
		List<Evaluate> evaluateList = photographerService
				.findEvaluateByPhId(photographer.getId());
		mv.addAttribute("theme", theme);
		mv.addAttribute("photographer", photographer);
		mv.addAttribute("photoThemeList", photoThemeList);
		mv.addAttribute("themeId", themeId);
		mv.addAttribute("evaluateList", evaluateList);
		mv.addAttribute("size", evaluateList.size());
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒专题摄影师样片
	 */
	@RequestMapping(value = "/kaSampleSer")
	public Model kaSampleSer(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeId = request.getParameter("themeId");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		Photographer photographer = photographerService
				.findPhotographerById(theme.getPhotographerId());
		// List<PhotoTheme>
		// photoThemeList=photographerService.findPhotoThemeById(theme.getPhotographerId());
		mv.addAttribute("theme", theme);
		mv.addAttribute("photographer", photographer);
		// mv.addAttribute("photoThemeList",photoThemeList);
		mv.addAttribute("themeId", themeId);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒专题选择预约
	 */
	@RequestMapping(value = "/kaAppointment")
	public ModelAndView kaAppointment(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String themeId = request.getParameter("themeId");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		if (userId != null && userId != "null") {
			StringBuffer sb = new StringBuffer();
			mv.addObject("theme", theme);
			Photographer photographer = photographerService
					.findPhotographerById(theme.getPhotographerId());
			 List<String>  listC = photographerService
					.selPotCl(theme.getPhotographerId());
			 if(listC.size()>0){
				 sb.append("[");
				 for(int j=0;j<listC.size();j++){
					 sb.append("'"+listC.get(j)+"',");
				 }
				 mv.addObject("scheduleClose",sb.toString().substring(0, sb.toString().length()-1)+"]");
			 }else{
				 mv.addObject("scheduleClose","[]");
			 }
			mv.addObject("photographer", photographer);
			mv.addObject("themeId", themeId);
			return mv;
		} else {
			mv.setViewName("kaLogin");
			request.getSession().setAttribute("THEMEID_BEFORE_LOGIN", themeId);
			return mv;
		}
	}

	/**
	 * Created by jifeng
	 * 咔嗒专题订单详情--------这时间我目前写成死的,以后要做可以改成活的,因为目前只在3月份测试我没时间,就写成了死值
	 */
	@RequestMapping("/kaOrderDet")
	public Model kaOrderDet(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String themeId = request.getParameter("themeId");
		int type = 0;
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));

		String scheduleDate = request.getParameter("scheduleDate");

		mv.addAttribute("scheduleDate", scheduleDate);

		mv.addAttribute("shotDate", scheduleDate);
		mv.addAttribute("theme", theme);
		mv.addAttribute("themeId", themeId);
		mv.addAttribute("type", type);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒专题确定预约,生成订单
	 */
	@RequestMapping(value = "/kaOrderPay")
	public Model kaOrderPay(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String themeId = request.getParameter("themeId");
		String shotDate = request.getParameter("shotDate");
		String scheduleDate = request.getParameter("scheduleDate");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		Photoorder photoorder = new Photoorder();
		photoorder.setPaymentStatus("未支付");
		photoorder.setPaymentType("微信支付");
		photoorder.setSendStatus("待付款");
		photoorder.setTotalMoney(theme.getPrice());
		photoorder.setNum(1);
		photoorder.setThemeId(Integer.valueOf(themeId));
		photoorder.setUserId(Integer.valueOf(userId));
		photoorder.setScheduleDate(scheduleDate);
		photoorder.setShotDate(shotDate);
		photographerService.addPhotoorder(photoorder);
		String orderCode = CreateOrder.formateCode(Integer.valueOf(userId),
				photoorder.getId());
		photographerService.updatePhotoorder(orderCode, photoorder.getId());
		request.getSession().setAttribute("realPayPrice", theme.getPrice());
		/* mv.addAttribute("totalMoney",theme.getPrice()); */
		mv.addAttribute("orderCode", orderCode);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒个人待拍摄主题列表
	 */
	@RequestMapping("/kaToShoots")
	public Model kaToShoots(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		// String userId ="1";
		List<OrderTheme> orderThemeList = photographerService
				.findOrderThemeByUserId(Integer.valueOf(userId));
		mv.addAttribute("orderThemeList", orderThemeList);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒个人待拍摄主题内容
	 */
	@RequestMapping("/kaToShoot")
	public Model kaToShoot(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String orderId = request.getParameter("orderId");
		OrderTheme orderTheme = photographerService.findOrderThemeById(Integer
				.valueOf(orderId));
		mv.addAttribute("orderTheme", orderTheme);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒个人待评价
	 */
	@RequestMapping(value = "/kdComment")
	public Model kdComment(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		// String userId ="1";
		List<OrderTheme> orderThemeList = photographerService
				.findOrderThemeByUserID(Integer.valueOf(userId));
		mv.addAttribute("orderThemeList", orderThemeList);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒个人待评价成功插入数据
	 */
	@RequestMapping(value = "/addEvaluate")
	public String addEvaluate(HttpServletRequest request,
			HttpServletResponse response) {
		String themeId = request.getParameter("themeId");
		String content = request.getParameter("content");
		String fruit = request.getParameter("Fruit");
		String orderId = request.getParameter("orderId");
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		Photographer photographer = photographerService
				.findPhotographerById(theme.getPhotographerId());
		Evaluate evaluate = new Evaluate();
		evaluate.setCotent(content);
		evaluate.setEva(fruit);
		evaluate.setPhotographerId(photographer.getId());
		evaluate.setUserName(photographer.getName());
		evaluate.setUserPicture(photographer.getHeadPortrait());
		photographerService.addEvaluate(evaluate);
		photographerService.updatePHOrder(Integer.valueOf(orderId));
		return "redirect:/kdIndex";
	}

	/**
	 * Created by jifeng 咔嗒个人资料
	 */
	@RequestMapping(value = "/kaModify")
	public Model kaModify(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		// String userId="5";
		User user = service.findUserById(Integer.valueOf(userId));
		mv.addAttribute("user", user);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒个人资料修改
	 */
	@RequestMapping("/updateUser")
	public String updateUser(HttpServletRequest request,
			HttpServletResponse response, @RequestParam MultipartFile[] myfiles)
			throws IllegalStateException, IOException {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		// String userId="5";
		User user = service.findUserById(Integer.valueOf(userId));
		String name = request.getParameter("name");
		String sex = request.getParameter("Sex");
		List list = new ArrayList();
		for (MultipartFile myfile : myfiles) {
			String fileName = myfile.getOriginalFilename();
			// 项目在容器中实际发布运行的根路径
			String realPath = request.getSession().getServletContext()
					.getRealPath("/")
					+ "image/user/";
			// 自定义的文件名称
			String trueFileName = String.valueOf(System.currentTimeMillis())
					+ fileName;
			// 设置存放图片文件的路径
			String path = realPath + trueFileName;
			String path1 = "/image/user/" + trueFileName;
			String ss = trueFileName.substring(trueFileName.length() - 4,
					trueFileName.length() - 3);
			// System.out.print(ss);
			// System.out.print(trueFileName);
			if (ss.equals(".")) {
				list.add(path1);
				System.out.println("存放图片文件的路径:" + path);
				myfile.transferTo(new File(path));
				System.out.println("文件成功上传到指定目录下");
			} else {
				list.add(user.getUserPicture());
			}
		}
		if (sex == null) {
			sex = user.getGender();
		}
		service.updateUser(list.get(0).toString(), name, sex,
				Integer.valueOf(userId));
		return "redirect:/kaPersonal";
	}

	/**
	 * Created by jifeng 咔嗒故事赞赏
	 */
	@RequestMapping("/appreciate")
	public String appreciate(HttpServletRequest request,
			HttpServletResponse response) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String themeId = request.getParameter("themeId");
		Appreciate appreciate = new Appreciate();
		appreciate.setThemeId(Integer.valueOf(themeId));
		appreciate.setUserId(Integer.valueOf(userId));
		photographerService.addAppreciate(appreciate);
		return "redirect:/kaStory?themeId=" + themeId + "";
	}

	/**
	 * Created by jifeng 咔嗒故事取消赞赏
	 */
	@RequestMapping("/deleteAppreciate")
	public String deleteAppreciate(HttpServletRequest request,
			HttpServletResponse response) {
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String themeId = request.getParameter("themeId");
		photographerService.deleteAppreciate(Integer.valueOf(themeId),
				Integer.valueOf(userId));
		return "redirect:/kaStory?themeId=" + themeId + "";
	}

	/**
	 * Created by jifeng 咔嗒订单列表(后台)
	 */
	@RequestMapping(value = "/photoorderList")
	public Model photoorderList(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		try {
			String pageNoStr = request.getParameter("pageNo");
			String pageSizeStr = request.getParameter("pageSize");

			int pageSize = 10;
			int currentPage = 1;
			if (!StringUtils.isEmpty(pageSizeStr))
				pageSize = Integer.parseInt(pageSizeStr);
			if (!StringUtils.isEmpty(pageNoStr))
				currentPage = Integer.parseInt(pageNoStr);
			if (currentPage < 1)
				currentPage = 1;
			String orderCode = request.getParameter("orderCode");
			Page page = photographerService.photoorderList(
					Integer.valueOf(currentPage), orderCode, pageSize);
			mv.addAttribute("page", page);
			List<OrderUser> orderUserList = page.getList();
			mv.addAttribute("orderUserList", orderUserList);
			mv.addAttribute("orderCode", orderCode);
		} catch (Exception e) {

			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒上传样片(后台)
	 */
	@RequestMapping(value = "/toAddSample")
	public Model toAddSample(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		// List<PhotoTheme> themeList =photographerService.findPhotoTheme();
		String userId = request.getParameter("userId");
		String themeId = request.getParameter("themeId");
		String orderId = request.getParameter("orderId");
		mv.addAttribute("userId", userId);
		mv.addAttribute("themeId", themeId);
		mv.addAttribute("orderId", orderId);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒保存样片(后台)
	 */
	@RequestMapping(value = "/addSample")
	public String addSample(HttpServletRequest request,
			HttpServletResponse response, @RequestParam MultipartFile[] myfiles)
			throws IllegalStateException, IOException {
		String userId = request.getParameter("userId");
		String themeId = request.getParameter("themeId");
		String orderId = request.getParameter("orderId");
		List list = new ArrayList();
		Sample sample = new Sample();
		for (MultipartFile myfile : myfiles) {
			String fileName = myfile.getOriginalFilename();
			// 项目在容器中实际发布运行的根路径
			String realPath = request.getSession().getServletContext()
					.getRealPath("/")
					+ "image/sample/";
			// 自定义的文件名称
			String trueFileName = String.valueOf(System.currentTimeMillis())
					+ fileName;
			// 设置存放图片文件的路径
			String path = realPath + trueFileName;
			String path1 = "/image/sample/" + trueFileName;
			// list.add(path1);
			sample.setThemeId(Integer.valueOf(themeId));
			sample.setUserId(Integer.valueOf(userId));
			sample.setPhotoes(path1);
			sample.setOrderId(Integer.valueOf(orderId));
			photographerService.addSample(sample);
			System.out.println("存放图片文件的路径:" + path);
			myfile.transferTo(new File(path));
			System.out.println("文件成功上传到指定目录下");
		}
		photographerService.updatePhotoOrder(Integer.valueOf(orderId));
		return "redirect:/photoorderList";
	}

	/**
	 * Created by jifeng 待选片列表
	 */
	@RequestMapping(value = "/kaMySelectPhoto")
	public Model kaMySelectPhoto(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		request.getSession().removeAttribute("listId");
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		List<OrderTheme> orderThemeList = photographerService
				.findOrderByStatus(Integer.valueOf(userId), "'已拍摄','待选片'");
		mv.addAttribute("orderThemeList", orderThemeList);
		return mv;
	}

	/**
	 * Created by jifeng 待收片列表
	 */
	@RequestMapping(value = "/kaMyConfirmPhoto")
	public Model kaMyConfirmPhoto(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		request.getSession().removeAttribute("listId");
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		List<OrderTheme> orderThemeList = photographerService
				.findOrderByStatus(Integer.valueOf(userId), "'待精修','已完成'");
		mv.addAttribute("orderThemeList", orderThemeList);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒选片列表
	 */
	@RequestMapping(value = "/kaMyPhoto")
	public Model kaMyPhoto(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		/*
		 * request.getSession().removeAttribute("listId"); String userId =
		 * String.valueOf(request.getSession().getAttribute("userId"));
		 * List<OrderTheme> orderThemeList =
		 * photographerService.findOrderByStatus(Integer.valueOf(userId));
		 * mv.addAttribute("orderThemeList",orderThemeList);
		 */
		return mv;
	}

	@RequestMapping(value = "/kaPromptWaiting")
	public String kaPromptWaiting(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String userConfirmDate = request.getParameter("userConfirmDate");
		String orderId = request.getParameter("orderId");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = userConfirmDate + " 23:59:59";
		Calendar calendar = Calendar.getInstance();
		long nowDate = calendar.getTime().getTime(); // Date.getTime() 获得毫秒型日期
		long intervalDate = 0;
		try {
			long specialDate = sdf.parse(dateString).getTime();
			intervalDate = (nowDate - specialDate) / (1000 * 60 * 60 * 24); // 计算间隔多少天，则除以毫秒到天的转换公式
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (intervalDate < 7)
			return "redirect:/kaMyUnDecoratedPhoto";
		else
			return "redirect:/kaMyDecoratedPhoto?orderId=" + orderId;
	}

	@RequestMapping(value = "/kaMyUnDecoratedPhoto")
	public Model kaMyUnDecoratedPhoto(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		return mv;
	}

	@RequestMapping(value = "/kaMyDecoratedPhoto")
	public Model kaMyDecoratedPhoto(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String orderIdStr = request.getParameter("orderId");
		int orderId = 0;
		if (!StringUtils.isEmpty(orderIdStr)) {
			orderId = Integer.parseInt(orderIdStr);
			OrderTheme orderTheme = photographerService
					.findOrderThemeById(orderId);
			if (orderTheme != null) {
				mv.addAttribute("orderTheme", orderTheme);
			}
		}
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒样片展示
	 */
	@RequestMapping(value = "/kaSelect")
	public Model kaSelect(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		// request.getSession().removeAttribute("listId");
		String themeId = request.getParameter("themeId");
		String orderId = request.getParameter("orderId");
		String userId = String.valueOf(request.getSession().getAttribute(
				"userId"));
		String selectId = request.getParameter("selectId");
		String ids = String
				.valueOf(request.getSession().getAttribute("listId"));
		Theme theme = photographerService.findThemeById(Integer
				.valueOf(themeId));
		List<Sample> sampleList = null;
		if (selectId == null || selectId != "null" && ids == "null") {
			sampleList = photographerService.findSampleList(
					Integer.valueOf(themeId), Integer.valueOf(userId),
					Integer.valueOf(orderId));
		}
		if (selectId != null && ids != "null") {
			sampleList = photographerService.findSampleNotByIds(
					Integer.valueOf(themeId), Integer.valueOf(userId), ids);
		}
		mv.addAttribute("sampleList", sampleList);
		mv.addAttribute("theme", theme);
		mv.addAttribute("orderId", orderId);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒样片预选
	 */
	@RequestMapping("/kaSelectConfirm")
	public Model kaSelectConfirm(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String ids = request.getParameter("ids");
		String themeId = request.getParameter("themeId");
		String orderId = request.getParameter("orderId");
		String idList = null;
		if (ids.substring(0, 1).equals(",")) {
			idList = ids.substring(1, ids.length());
		} else {
			idList = ids.substring(0, ids.length());
		}
		List<Sample> sampleList = photographerService.findSampleByids(idList);
		mv.addAttribute("sampleList", sampleList);
		mv.addAttribute("themeId", themeId);
		mv.addAttribute("ids", idList);
		mv.addAttribute("orderId", orderId);
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒样片重新选择
	 */
	@RequestMapping(value = "/toSelect")
	public String toSelect(HttpServletRequest request,
			HttpServletResponse response) {
		// request.getSession().removeAttribute("listId");
		String ids = request.getParameter("ids");
		String themeId = request.getParameter("themeId");
		String orderId = request.getParameter("orderId");
		String idList = ids.substring(1, ids.length());
		request.getSession().setAttribute("listId", idList);
		return "redirect:/kaSelect?themeId=" + themeId + "&selectId=1&orderId="
				+ orderId + "";
	}

	/**
	 * Created by jifeng 咔嗒确认选择样片
	 */
	@RequestMapping(value = "/addSelectSample")
	public String addSelectSample(HttpServletRequest request,
			HttpServletResponse response) {
		String sampleIds = request.getParameter("idss");
		// String themeId=request.getParameter("themeIds");
		String orderId = request.getParameter("orderId");
		SelectPhoto selectPhoto = new SelectPhoto();
		selectPhoto.setSampleList(sampleIds);
		selectPhoto.setOrderId(Integer.valueOf(orderId));
		// List<Sample> sampleList =
		// photographerService.findSampleByids(sampleIds);
		// Sample sample = sampleList.get(0);
		photographerService.updateSampleByids(sampleIds);
		photographerService.updateSamplOrder(Integer.valueOf(orderId));
		return "redirect:/kaMyConfirmPhoto";
	}

	/**
	 * Created by jifeng 咔嗒确认选择样片(后台列表)
	 */
	@RequestMapping(value = "/confirmSelect")
	public Model confirmSelect(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		try {
			String pageNo = request.getParameter("pageNo");
			if (pageNo == null) {
				pageNo = "1";
			}
			String orderCode = request.getParameter("orderCode");
			Page page = photographerService.findOrderByStatus(
					Integer.valueOf(pageNo), orderCode, 10);
			mv.addAttribute("page", page);
			List<OrderUser> orderUserList = page.getList();
			mv.addAttribute("orderCode", orderCode);
			mv.addAttribute("orderUserList", orderUserList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * Created by jifeng 咔嗒查看选择样片(后台)
	 */
	@RequestMapping(value = "/sampleDetail")
	public Model sampleDetail(HttpServletRequest request,
			HttpServletResponse response, Model mv) {
		String orderId = request.getParameter("orderId");
		List<SelectPhoto> selectPhotoList = photographerService
				.findSelectPhotoByOrderId(Integer.valueOf(orderId));
		List<Sample> sampleList = photographerService
				.findSampleByIdList(selectPhotoList.get(0).getSampleList());
		mv.addAttribute("sampleList", sampleList);
		return mv;
	}
	
	
	/**
	 * Created by huanghaiming 档期管理(后台)
	 */
	 @RequestMapping(value = "/scheduleManage")
	 public String scheduleManagement(HttpServletRequest request){
		return "redirect:/scheduleManagement";
	 }
	 
	 /**
	  * Created by huanghaiming 
	  */
	 @RequestMapping(value = "/scheduleManagement")
	 public Model scheduleMan(HttpServletRequest request,HttpServletResponse response,Model mv){
		 String id = request.getParameter("id");
		 List<Photographer> list = photographerService.selPhotographer();//获取摄影师下拉
		 StringBuffer sb = new StringBuffer();
		 StringBuffer sber = new StringBuffer();
		 if(list.size()>0){
			 Photographer photographer = list.get(0);
			 List<String> listP = null;//获取订单预约时间
			 List<String> listC = null;//档期关闭日期
			 if(id==null || "null".equals(id.toString())){
				 listP = photographerService.selPotOr(photographer.getId());
				 listC = photographerService.selPotCl(photographer.getId());
			 }else{
				 listP = photographerService.selPotOr(Integer.valueOf(id));
				 listC = photographerService.selPotCl(Integer.valueOf(id));
			 }
			 if(listP.size()>0){
				 sb.append("[");
				 for(int i=0;i<listP.size();i++){
					 sb.append("'"+listP.get(i)+"',");
				 }
				 mv.addAttribute("scheduleDate",sb.toString().substring(0, sb.toString().length()-1)+"]");
			 }else{
				 mv.addAttribute("scheduleDate","[]");
			 }
			 
			 if(listC.size()>0){
				 sber.append("[");
				 for(int j=0;j<listC.size();j++){
					 sber.append("'"+listC.get(j)+"',");
				 }
				 mv.addAttribute("scheduleClose",sber.toString().substring(0, sber.toString().length()-1)+"]");
			 }else{
				 mv.addAttribute("scheduleClose","[]");
			 }
		 }
		 mv.addAttribute("photographer", list);
		return mv;
	 }
	 
	 
      /**
	  * Created by huanghaiming 
	 * @throws IOException 
	  */
	 @RequestMapping(value = "/scduleManagement")
	 public void scduleManagement(HttpServletRequest request,HttpServletResponse response,Model mv) throws IOException{
		 String id = request.getParameter("id");
		 List<String> listP = photographerService.selPotOr(Integer.valueOf(id));//获取订单预约时间
		 List<String>  listC = photographerService.selPotCl(Integer.valueOf(id));//档期关闭日期
		 StringBuffer sb = new StringBuffer();
		 StringBuffer sber = new StringBuffer();
		 String scheduleDate = "[]";
		 String scheduleClose = "[]";
		 if(listP.size()>0){
			 sb.append("[");
			 for(int i=0;i<listP.size();i++){
				 sb.append("'"+listP.get(i)+"',");
			 }
			 scheduleDate = sb.toString().substring(0, sb.toString().length()-1)+"]";
		 }
		 
		 if(listC.size()>0){
			 sber.append("[");
			 for(int j=0;j<listC.size();j++){
				 sber.append("'"+listC.get(j)+"',");
			 }
			 scheduleClose = sber.toString().substring(0, sber.toString().length()-1)+"]";
		 }
		 response.getWriter().write(
					"{\"scheduleDate\":\"" + scheduleDate + "\",\"scheduleClose\":\"" + scheduleClose + "\"}");
	 }
	 
	 
	/**
	  * Created by huanghaiming 
	 * @throws IOException 
	  */
	 @RequestMapping(value = "/scheduleClose")
	 public void addSchedule(HttpServletRequest request,HttpServletResponse response,Model mv) throws IOException{
		 String id = request.getParameter("id");
		 String schedleDate = request.getParameter("scheduleDate");
		 List<Integer> li = photographerService.selLi(id,schedleDate);
		 if(li.size()>0){
			 photographerService.delSchedule(id,schedleDate);
		 }else{
			 photographerService.addSchedule(id,schedleDate);
		 }
		 List<String> listP = photographerService.selPotOr(Integer.valueOf(id));//获取订单预约时间
		 List<String>  listC = photographerService.selPotCl(Integer.valueOf(id));//档期关闭日期
		 StringBuffer sb = new StringBuffer();
		 StringBuffer sber = new StringBuffer();
		 String scheduleDate = "[]";
		 String scheduleClose = "[]";
		 if(listP.size()>0){
			 sb.append("[");
			 for(int i=0;i<listP.size();i++){
				 sb.append("'"+listP.get(i)+"',");
			 }
			 scheduleDate = sb.toString().substring(0, sb.toString().length()-1)+"]";
		 }
		 if(listC.size()>0){
			 sber.append("[");
			 for(int j=0;j<listC.size();j++){
				 sber.append("'"+listC.get(j)+"',");
			 }
			 scheduleClose = sber.toString().substring(0, sber.toString().length()-1)+"]";
		 }
		 response.getWriter().write(
					"{\"scheduleDate\":\"" + scheduleDate + "\",\"scheduleClose\":\"" + scheduleClose + "\"}");
	 }

}
